<template>
  <van-nav-bar title="用户注册" :fixed="true" left-arrow @click-left="$router.back()"/>
  <van-form @submit="onSubmit" class="mt100">
    <van-cell-group inset>
      <van-field
        v-model="name"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="text"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="password_confirmation"
        type="text"
        name="确认密码"
        label="确认密码"
        placeholder="确认密码"
        :rules="[{ required: true, message: '请填写确认密码' }]"
      />
      <van-field
        v-model="email"
        type="email"
        name="邮箱"
        label="邮箱"
        placeholder="邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
      />
    </van-cell-group>
    <div class="login" @click.stop="router.push('/login')">已有账号？立即登录</div>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import { register } from '@/api/login'
import {useRouter} from 'vue-router';
import { ref } from 'vue'
import { Toast } from 'vant'

  const router = useRouter()
  const name = ref<string>('');
  const password = ref<string>('');
  const password_confirmation = ref<string>('');
  const email = ref<string>('');

  const onSubmit = async () => {
    let list = {
      name:name.value,
      password:password.value,
      password_confirmation:password_confirmation.value,
      email:email.value
    } as any
    let res = await register(list)
    
    let err = ''
    if(res.status === 201){
      router.back()
      Toast.success('注册成功！');
    }else if(res.status === 422){
      if(res.data.errors.email){
        err = res.data.errors.email[0]
      }else if(res.data.errors.name){
        err = res.data.errors.name[0]
      }else{
        err = res.data.errors.password[0]
      }
      Toast.fail(err);
    }else if(res.status === 401){
      Toast.fail('用户名或密码错误');
    }
    
  };

</script>

<style scoped lang="less">
.login {
  padding: 32px;
  color: blue;
  font-size: 14px;
}
</style>